package com.wzk.travelspringboot.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wzk.travelspringboot.dao.BlogCommentDAO;
import com.wzk.travelspringboot.dao.BlogDAO;
import com.wzk.travelspringboot.dao.UserDAO;
import com.wzk.travelspringboot.dto.BlogCommentDTO;
import com.wzk.travelspringboot.dto.Result;
import com.wzk.travelspringboot.entity.Blog;
import com.wzk.travelspringboot.entity.BlogComment;
import com.wzk.travelspringboot.service.BlogCommentService;
import com.wzk.travelspringboot.vo.BlogCommentVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * @Author: WangZiKang
 * @Date: 2025/1/15 21:13
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class BlogCommentServiceImpl extends ServiceImpl<BlogCommentDAO,BlogComment> implements BlogCommentService {

    private final BlogCommentDAO dao;

    private final BlogDAO blogDAO;

    private final UserDAO userDAO;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result comment(BlogCommentDTO dto) {
        //1.查询这条动态是否存在
        Blog blog = blogDAO.selectById(dto.getBlogId());
        if (blog == null || blog.getIsDelete() == 1){
            return Result.failed("此动态已经不存在了");
        }
        //2.数据插入数据库中
        BlogComment blogComment = BeanUtil.copyProperties(dto, BlogComment.class);
        blogComment.setLikeTotal(0L);
        blogComment.setIsDelete(0);
        blogComment.setCreateTime(LocalDateTime.now());
        blogComment.setUpdateTime(LocalDateTime.now());
        boolean b = save(blogComment);
        if (!b){
            return Result.failed("评论失败出现未知错误！请联系管理员");
        }
        //3.查询用户昵称
        String nickName = userDAO.queryNickNameById(dto.getUserId());
        BlogCommentVO vo = new BlogCommentVO();
        vo.setId(blogComment.getId());
        vo.setContent(blogComment.getContent());
        vo.setNickName(nickName);
        vo.setUserId(dto.getUserId());
        //4.返回结果
        return Result.success("评论成功",vo);
    }
}
